package cn.edu.nju.ws.sview.group;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.util.URIUtil;
import cn.edu.nju.ws.sview.views.Entity;
import cn.edu.nju.ws.sview.views.Group;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing.QuadItem;
import cn.edu.nju.ws.sview.wyge.relations.adataset.CustomDataset;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.Relation;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.Relations;
import cn.edu.nju.ws.sview.wyge.relations.datasets.DatasetBrowsing;
import cn.edu.nju.ws.sview.wyge.relations.datasets.DatasetItem;

public class ProfileServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml;charset=utf-8");
		String param = null;
		JSONObject reqJSON = null;
		JSONObject result = new JSONObject();
		if((param = request.getParameter("summaryDiv"))!=null){
			reqJSON = (JSONObject) JSONValue.parse(param);
			int gid = Integer.valueOf((String)reqJSON.get("gid"));
			String lang = (String) reqJSON.get("lang");
			//=====to be completed=====
			String summary = "The summary of this group.";
			if(lang.contentEquals("zh")){
				summary = "本编辑组的简介。";
			}
			//=========================
			result.put("type", "string");
			result.put("result", summary);
			
		}else if((param = request.getParameter("membersDiv")) != null){
			reqJSON = (JSONObject) JSONValue.parse(param);
			int gid = Integer.valueOf((String)reqJSON.get("gid"));
			String lang = (String) reqJSON.get("lang");
			String content = null;
			ArrayList<String> memNames = Group.getMembers(gid);
			StringBuffer sb = new StringBuffer();
			if(lang.contentEquals("zh")){
				sb.append("<tr><th>编辑组成员</th></tr>");
			}else{
				sb.append("<tr><th>Member Name</th></tr>");
			}
			for(String name : memNames){
				sb.append("<tr><td>"+name+"</td></tr>");
			}
			content = sb.toString();
			result.put("type", "table");
			result.put("result", content);
		}else if((param = request.getParameter("entitiesDiv")) != null){
			reqJSON = (JSONObject) JSONValue.parse(param);
			int gid = Integer.valueOf((String)reqJSON.get("gid"));
			String lang = (String)reqJSON.get("lang");
			String content = null;
			StringBuffer sb = new StringBuffer();
			if(lang.contentEquals("zh")){
				sb.append("<tr><th>实体名</th></tr>");
			}else{
				sb.append("<tr><th>Entity Name</th></tr>");
			}
			ArrayList<QuadItem> elist = new ArrayList<EntityBrowsing.QuadItem>();
			boolean flag = EntityBrowsing.fetchGroupEntities(gid, 0, -1, lang, elist);
			if(flag){
				for(QuadItem qi : elist){
					int id = qi.getId();
					int genre = qi.getGenre();
					String genre_str = URIUtil.getItemTypeStr(genre);
					String name = qi.getName();
					sb.append("<tr id='"+genre_str+id+"'><td><a href='/sview/entity/e"+id+"'>"+name+"</a></td></tr>");
				}
			}
			content = sb.toString();
//			try {
//				Connection conn = DBConnectionFactory.getConnection();
//				PreparedStatement pstmt = conn.prepareStatement("select id,name from identity where group_id=? order by id");
//				pstmt.setInt(1, gid);
//				ResultSet rs = pstmt.executeQuery();
//				StringBuffer sb = new StringBuffer();
//				sb.append("<tr><th>Name</th></tr>");
//				while(rs.next()){
//					sb.append("<tr id='e"+rs.getInt(1)+"'><td><a href='/sview/entity/e"+rs.getInt(1)+"'>"+rs.getString(2)+"</a></td></tr>");
//				}
//				content = sb.toString();
//				rs.close();
//				pstmt.close();
//				conn.close();
//			} catch (SQLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			result.put("type", "table");
			result.put("result", content);
		}else if((param = request.getParameter("viewsDiv")) != null){
			reqJSON = (JSONObject) JSONValue.parse(param);
			int gid = Integer.valueOf((String)reqJSON.get("gid"));
			String lang = (String)reqJSON.get("lang");
			String content = null;
			try {
				Connection conn = DBConnectionFactory.getConnection();
				PreparedStatement pstmt = conn.prepareStatement("select id,name,use_times from view where group_id=? order by id");
				pstmt.setInt(1, gid);
				ResultSet rs = pstmt.executeQuery();
				StringBuffer sb = new StringBuffer();

				if(lang.contentEquals("zh")){
					sb.append("<tr><th>视图名</th><th>使用次数</th></tr>");
				}else{
					sb.append("<tr><th>View Name</th><th>Use Times</th></tr>");
				}
				while(rs.next()){
					sb.append("<tr id='v"+rs.getInt(1)+"'><td>"+rs.getString(2)+"</td><td>"+rs.getInt(3)+"</td></tr>");
				}
				content = sb.toString();
				rs.close();
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			result.put("type", "table");
			result.put("result", content);
		}else if((param = request.getParameter("datasetsDiv")) != null){
			reqJSON = (JSONObject) JSONValue.parse(param);
			int gid = Integer.valueOf((String)reqJSON.get("gid"));
			String lang = (String)reqJSON.get("lang");
			String content = null;
//			try {
				ArrayList<DatasetItem> dslist = DatasetBrowsing.fetchGroupAll(gid, 0, -1);
				StringBuffer sb = new StringBuffer();
				if(lang.contentEquals("zh")){
					sb.append("<tr><th>数据集名</th><th>更新时间</th></tr>");
				}else{
					sb.append("<tr><th>Dataset Name</th><th>Update Time</th></tr>");
				}
				for(DatasetItem di : dslist){
					int ds_id = di.getId();
					String name = DatasetItem.getShowNameByDatasetID(di, lang);
					sb.append("<tr id='d"+ds_id+"'><td><a href='/sview/dataset/c"+ds_id+"'>"+name+"</a></td><td>"+CustomDataset.getUpdateDateByCustomDatasetID(ds_id, "yyyy/MM/dd")+"</td></tr>");
				}
				content = sb.toString();
//				Connection conn = DBConnectionFactory.getConnection();
//				PreparedStatement pstmt = conn.prepareStatement("select id,name from custom_dataset where group_id=? order by id");
//				pstmt.setInt(1, gid);
//				ResultSet rs = pstmt.executeQuery();
//				StringBuffer sb = new StringBuffer();
//				sb.append("<tr><th>Name</th><th>Create Time</th></tr>");
//				while(rs.next()){
//					int ds_id = rs.getInt(1);
//					sb.append("<tr id='d"+ds_id+"'><td><a href='/sview/dataset/c"+ds_id+"'>"+rs.getString(2)+"</a></td><td>"+CustomDataset.getCreatedDateByCustomDatasetID(ds_id, "yyyy/MM/dd")+"</td></tr>");
//				}
//				content = sb.toString();
//				rs.close();
//				pstmt.close();
//				conn.close();
//			} catch (SQLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			result.put("type", "table");
			result.put("result", content);
		}else if((param = request.getParameter("relationsDiv")) != null){
			reqJSON = (JSONObject) JSONValue.parse(param);
			int gid = Integer.valueOf((String)reqJSON.get("gid"));
			String lang = (String)reqJSON.get("lang");
			String content = null;
			ArrayList<Relation> array = Relations.getRelationsByGroupId(gid);
			StringBuffer sb = new StringBuffer();
			if(lang.contentEquals("zh")){
				sb.append("<tr><th>关系名</th><th>创建时间</th></tr>");
			}else{
				sb.append("<tr><th>Relation Name</th><th>Create Time</th></tr>");
			}
			for(Relation item : array){
				String roles = "";
				for(String role : item.getRoles()){
					roles += role + ",";
				}
				roles = roles.substring(0, roles.length()-1);
				sb.append("<tr id='r"+item.getRelationID()+"'><td>"+item.getName()+"("+roles+")"+"</td><td>"+item.getDate()+"</td></tr>");
			}
			content = sb.toString();
			result.put("type", "table");
			result.put("result", content);
		}else{
			result.put("type", "error");
			result.put("result", request.getParameterNames().toString());
		}
		
//		System.out.println("result"+result.toJSONString()+"\tsize:"+result.size());
		response.getWriter().print(result);
	}

}
